package com.youhome.housing.config;

import com.youhome.service.model.CompanyToken;
import com.youhome.service.service.CompanyTokenService;
import com.youhome.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class ApplicationEventListener implements ApplicationListener<ApplicationReadyEvent> {
    @Autowired
    private CompanyTokenService CompanyTokenService;

    /**
     * 为 company 生成 token
     * @param applicationReadyEvent
     */
    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {

        List<CompanyToken> companyTokens = CompanyTokenService.selectByAll();
        for (CompanyToken item : companyTokens) {

            if (StringUtils.isEmpty(item.getTokenValue())) {

                Map<String,Object> map = new HashMap<>();
                map.put("TokenId",item.getTokenId());
                map.put("CompanyId",item.getCompanyId());
                map.put("TokenName",item.getTokenName());

                String token = TokenUtils.createToken(map, item.getIndate());

                CompanyToken entity = new CompanyToken();
                entity.setTokenId(item.getTokenId());
                entity.setTokenValue(token);

                CompanyTokenService.updateByPrimaryKeySelective(entity);
            }
        }
    }


}

